import { httpEvent } from "@/composables/useApiFetch";
import { useNotification } from "@/composables/useNotification";
import { useUserStore } from "@/stores/user";

export default defineComponent({
  setup() {
    const notification = useNotification();
    const router = useRouter();
    const userStore = useUserStore();
    // 统一处理 http 事件
    httpEvent.on("response", (ctx) => {
      const { message, success } = ctx.data;
      if (message) {
        if (success) {
          notification.success(message);
        } else notification.error(message);
      }
    });
    // 统一处理错误
    httpEvent.on("error", (ctx) => {
      if (ctx.response?.status == 401) {
        // 用户登录过期，则将全局状态重置。
        userStore.logout();
        return router.push({ name: "login" });
      }
      const message = ctx.data?.message;
      if (message) {
        notification.error(message, {
          title: "服务器运行错误",
        });
      }
    });
    // 返回渲染函数
    return () => false;
  },
});
